﻿namespace DCHealthCheck.MvcWeb.Controllers {

    #region Usings
    using DCHealthCheck.Common;
using DCHealthCheck.DomainModel;
using DCHealthCheck.MvcWeb.Classes;
using DCHealthCheck.MvcWeb.Classes.DataServices;
using DCHealthCheck.MvcWeb.Classes.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
    #endregion

    public class ResultsController : BaseController {

        private readonly IRepository<SystemInfo, IEntityManager> ResultsRepository;
        private readonly IResultsDataService ResultsDataService;

        public ResultsController(IRepository<SystemInfo, IEntityManager> resultsRepository, IResultsDataService resultsDataService) {
            this.ControllerName = "Results";
            this.ResultsRepository = resultsRepository;
            this.ResultsDataService = resultsDataService;
        }

        [Authorize(Roles = Global.AdminRole)]
        [HttpPost]
        public ActionResult Delete(Guid id) {
            bool success = false;

            var systemInfo = this.ResultsRepository.Find(x => x.Id == id).FirstOrDefault();
            if (systemInfo != null) {
                systemInfo.DetachedState = DetachedState.Deleted;
                this.ResultsRepository.Delete(systemInfo);
                this.ResultsRepository.Save();
                success = this.ResultsRepository.Get(x => x.Id == id) == null;
            }

            return success ? new HttpStatusCodeResult(200, "Ok") : new HttpStatusCodeResult(500, "Error occurred performing the requested action.");
        }

        public ActionResult Details(ResultsViewModel viewModel) {
            this.ResultsDataService.ProcessData(viewModel);
            return View(viewModel);
        }

        /// <summary>
        /// Download a comma separated value list of HealthCheck results
        /// </summary>
        /// <param name="viewModel">The ViewModel</param>
        /// <param name="token">The download token</param>
        /// <returns>The file results</returns>
        [EnableCompression]
        [HttpPost]
        public FileContentResult Download(ResultsViewModel viewModel, string token) {
            string fileName = string.Format("HealthCheckResults_{0}.csv", DateTime.UtcNow.ToString("yyyy-MM-dd-HHmmss"));
            string fileData = this.ResultsDataService.GetCSVData(viewModel);

            HttpContext.Response.AppendCookie(new HttpCookie("fileDownloadToken", token));
            return File(fileData.ToByteArray(Encoding.UTF8), "application/octet-stream", fileName);
        }

        /// <summary>
        /// Download a GPO Report for the specified HealthCheck SystemInfo Id
        /// </summary>
        /// <param name="systemInfoId">The HealthCheck SystemInfo Id</param>
        /// <param name="reportType">The report type, XML or HTML</param>
        /// <returns>The file results</returns>
        [EnableCompression]
        public FileContentResult Download(Guid systemInfoId, string reportType) {
            string fileName = systemInfoId.ToString() + reportType;

            var systemInfo = this.ResultsRepository.Get(x => x.DomainController)
                .Where(x => x.Id == systemInfoId)
                .FirstOrDefault();

            string fileData = string.Empty;

            if (systemInfo != null) {
                fileName = string.Format("{0}_GpReport_{1}.{2}",
                    systemInfo.DomainController.SamAccountNameFriendly,
                    systemInfo.CheckDateTimeUTC.ToString("yyyy-MM-dd-HHmmss"),
                    reportType);

                if (string.Equals(reportType, "html", StringComparison.OrdinalIgnoreCase)) {
                    if (systemInfo.GpRsopHtml != null) {
                        fileData = systemInfo.GpRsopHtml.FromCompressedByteArray();
                    }
                }
                else if (string.Equals(reportType, "xml", StringComparison.OrdinalIgnoreCase)) {
                    if (systemInfo.GpRsopXml != null) {
                        fileData = systemInfo.GpRsopXml.FromCompressedByteArray();
                    }
                }
            }

            Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName);
            return File(fileData.ToByteArray(Encoding.Unicode), "application/octet-stream", fileName);
        }

        public ActionResult Index(ResultsViewModel viewModel) {
            this.ResultsDataService.ProcessData(viewModel);
            return View(viewModel);
        }
    }
}
